import json
from pathlib import Path
from typing import Dict, Optional

SUPPORTED_LANGUAGES = ("zh", "en")


class I18N:
    """Simple JSON-based localization helper."""

    _instance = None

    def __init__(self):
        self._language = "zh"
        self._messages: Dict[str, Dict[str, str]] = {}
        self._messages_path = Path(__file__).parent / "locales" / "messages.json"
        self._load_messages()

    def _load_messages(self):
        if not self._messages_path.exists():
            self._messages = {}
            return
        try:
            with open(self._messages_path, "r", encoding="utf-8") as f:
                data = json.load(f)
                if isinstance(data, dict):
                    self._messages = data
                else:
                    self._messages = {}
        except Exception:
            self._messages = {}

    @classmethod
    def instance(cls) -> "I18N":
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

    def set_language(self, language: Optional[str]):
        if language and language in SUPPORTED_LANGUAGES:
            self._language = language
        else:
            self._language = "zh"

    def get_language(self) -> str:
        return self._language

    def translate(self, key: str, **kwargs) -> str:
        entry = self._messages.get(key, {})
        text = entry.get(self._language) or entry.get("zh") or entry.get("en") or key
        if kwargs:
            try:
                return text.format(**kwargs)
            except KeyError:
                return text
        return text


def set_language(language: Optional[str]):
    I18N.instance().set_language(language)


def get_language() -> str:
    return I18N.instance().get_language()


def t(key: str, **kwargs) -> str:
    return I18N.instance().translate(key, **kwargs)


def get_supported_languages():
    return SUPPORTED_LANGUAGES

